<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="$t('pageFirmware.updateBiosReference')"
    width="500"
  >
    <el-form :model="form" :rules="rules">
      <el-form-item
        :label="$t('trustedComputing.modal.userName')"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.userName" autocomplete="off" />
      </el-form-item>
      <el-form-item
        :label="$t('trustedComputing.modal.newPassword')"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.password" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeModal">
          {{ $t('global.action.cancel') }}
        </el-button>
        <el-button type="primary" @click="onOk">
          {{ $t('global.action.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import useVuelidateTool from '@/hooks/useVuelidateTool';

const dialogFormVisible = ref(false);
defineExpose({ dialogFormVisible });

const formLabelWidth = '140px';
const emit = defineEmits(['ok']);

const { useVuelidate, required, elementInputValidator } = useVuelidateTool();

const form = reactive({
  userName: '',
  password: '',
});

const v$ = useVuelidate(
  {
    userName: {
      required,
    },
    password: {
      required,
    },
  },
  form,
);

const rules = computed(() => {
  return {
    sessionTimeout: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'sessionTimeout'),
      },
    ],
  };
});

const onOk = (bvModalEvt: { preventDefault: () => void }) => {
  // prevent modal close
  bvModalEvt.preventDefault();
  handleSubmit();
};
const closeModal = () => {
  nextTick(() => {
    dialogFormVisible.value = false;
    form.userName = '';
    form.password = '';
    v$.value.$reset();
  });
};
const handleSubmit = async () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  closeModal();
  emit('ok', form.userName, form.password);
};
</script>
